import 'package:casdon/core/utils/first_launch_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:casdon/core/logger/log.dart';

// 存储用户敏感信息，如：id，pwd，token等
class AuthStorage extends StateNotifier<bool> {
  static const _initializationFlagKey = 'auth_storage_initialized';
  static const _androidOptions = AndroidOptions(
    encryptedSharedPreferences: true,
  );

  final FlutterSecureStorage _storage = const FlutterSecureStorage();

  // 构造函数，初始状态为false（未登录）
  AuthStorage() : super(false) {
    _initialize();
  }

  // 公开的getter，用于外部判断登录状态
  bool get isLoggedIn => state;

  Future<void> _initialize() async {
    await _ensureFirstLaunchCleanup();
    await _initializeLoginStatus();
  }

  Future<void> _ensureFirstLaunchCleanup() async {
    final isFirstLaunch = await FirstLaunchService.instance.isFirstLaunch();
    if (!isFirstLaunch) {
      return;
    }
    await _storage.deleteAll(aOptions: _androidOptions);
    await _storage.write(
      key: _initializationFlagKey,
      value: 'true',
      aOptions: _androidOptions,
    );
    await FirstLaunchService.instance.markLaunched();
    state = false;
    Log.d("首次启动，已清理敏感数据", tag: "AuthStorage");
  }

  // 初始化时检查登录状态
  Future<void> _initializeLoginStatus() async {
    final token = await getToken();
    final isLoggedIn = token != null && token.isNotEmpty;
    state = isLoggedIn;
    Log.d("Login status initialized: $isLoggedIn", tag: "AuthStorage");
  }

  Future<void> saveToken(String token) async {
    await _storage.write(key: 'token', value: token, aOptions: _androidOptions);

    // 保存token后更新登录状态
    state = true;
    Log.d("token 已经保存", tag: "AuthStorage");
  }

  Future<String?> getToken() async {
    return await _storage.read(key: 'token', aOptions: _androidOptions);
  }

  Future<void> savePwd(String password) async {
    await _storage.write(
      key: 'password',
      value: password,
      aOptions: _androidOptions,
    );
  }

  Future<String?> getPwd() async {
    return await _storage.read(key: 'password', aOptions: _androidOptions);
  }

  Future<void> saveUserId(String userId) async {
    await _storage.write(
      key: 'userId',
      value: userId,
      aOptions: _androidOptions,
    );
  }

  Future<String?> getUserId() async {
    return await _storage.read(key: 'userId', aOptions: _androidOptions);
  }

  Future<String?> getUserAccount() async {
    final ret = await _storage.read(key: 'account', aOptions: _androidOptions);
    return ret;
  }

  Future<void> saveUserAccount(String account) async {
    await _storage.write(
      key: 'account',
      value: account,
      aOptions: _androidOptions,
    );
  }

  Future<void> saveNickName(String nickName) async {
    await _storage.write(
      key: 'nickName',
      value: nickName,
      aOptions: _androidOptions,
    );
  }

  Future<String?> getNickName() async {
    return await _storage.read(key: 'nickName', aOptions: _androidOptions);
  }

  // 检查是否已认证（异步验证并更新状态）
  Future<bool> isAuthenticated() async {
    final token = await getToken();
    final authenticated = token != null && token.isNotEmpty;
    state = authenticated;
    return authenticated;
  }

  // 登出方法
  Future<void> logout() async {
    await _storage.deleteAll(aOptions: _androidOptions);
    await _storage.write(
      key: _initializationFlagKey,
      value: 'true',
      aOptions: _androidOptions,
    );

    // 清除数据后更新登录状态
    state = false;
    Log.d("User logged out, storage cleared", tag: "AuthStorage");
  }

  // 保持向后兼容的clear方法
  Future<void> clear() async {
    await logout();
  }

  Future<void> debugPrintAll() async {
    final all = await _storage.readAll(aOptions: _androidOptions);
    Log.d("All stored: $all", tag: "AuthStorage");
  }
}

// AuthStorage Provider - 直接提供登录状态监听
final authStorageProvider = StateNotifierProvider<AuthStorage, bool>((ref) {
  return AuthStorage();
});
